import { Request, Response } from "express";
import Behavior from "../models/Behavior";
import geoip from "geoip-lite";
import moment from "moment";
import { faker } from "../../app";
import { getChineseIp } from "../../utils";

export const trackBehavior = async (req: Request, res: Response) => {
    try {
        const { page, timestamp, userAgent, remark } = req.body;
        const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "";
        console.log(`trackBehavior ip: ${ip}, ${moment().format("YYYY-MM-DD HH:mm:ss")}`);
        const location = geoip.lookup(ip as string);
        const currentTimestamp = new Date();

        // 检查最近3小时内是否有记录
        const threeHoursAgo = moment().subtract(3, "hours").toDate();
        const existingRecord = await Behavior.findOne({
            ip,
            userAgent,
            timestamp: { $gte: threeHoursAgo },
        });

        if (!existingRecord) {
            const behavior = new Behavior({
                page,
                timestamp,
                ip,
                userAgent,
                location,
                remark,
                createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
                updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
            });
            await behavior.save();

            res.status(200).json({
                status: "ok",
                message: "Behavior tracked successfully",
            });
        } else {
            res.status(200).json({
                status: "ok",
                message: "Behavior already tracked within 3 hours",
            });
        }
    } catch (error: any) {
        console.error("error:", error);
        res.status(500).json({ error: error.message });
    }
};

export const generateBehaviors = async (req: any, res: any) => {
    const addNumber = 1233;
    try {
        let count = 0;
        for (let i = 0; i < addNumber; i++) {
            const page = "/home";
            const timestamp = faker.date.between({
                from: "2022-12-22",
                to: moment().add(1, "months").format("YYYY-MM-DD"),
            });
            const remark = "访问首页";
            const ip = getChineseIp();
            const location = geoip.lookup(ip as string);
            const userAgent = faker.internet.userAgent();

            // 生成日期
            const createdAt = moment(timestamp).format("YYYY-MM-DD HH:mm:ss");
            const newBehavior = new Behavior({
                page,
                timestamp,
                ip,
                userAgent,
                location,
                remark,
                createdAt,
                updatedAt: createdAt,
            });
            const behavior = await newBehavior.save();
            if (behavior) {
                count++;
            }
        }
        console.log("count::", count);
        if (count === addNumber) {
            res.status(201).send("批量生成行为数据成功");
        }
    } catch (error: any) {
        console.error("error:", error);
        res.status(500).json({ error: error.message });
    }
};
